﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Lifang.Dao;
using System.Text;
using System.Net.Http.Headers;
using Lifang.Common;
using Microsoft.AspNetCore.Hosting;
using Lifang.Entites;

namespace Lifang.API.Controllers
{
    [Produces("application/json")]
    [Route("api/Tools")]
    public class ToolsController : BaseController
    {
        private readonly IHostingEnvironment hostingEnv;

        public ToolsController(IHostingEnvironment hostingEnvironment)
        {
            hostingEnv = hostingEnvironment;
        }     
        
        [HttpGet("Test")]
        public ActionResult Test()
        {
            string filePath = hostingEnv.ContentRootPath + $@"\Upload\";
            return Json(new {
                path = filePath
            });
        }



        [HttpPost]
        public IActionResult UpLoadProcess()
        {
            CommonResult result = new CommonResult();
            var files = Request.Form.Files;
            var id = Request.Form["id"];
            long size = files.Sum(f => f.Length);
            if(files.Count<=0)
            {
                result.Success = false;
                result.Message = "你没有选择要上传的文件";
                return Json(result);
            }

            if (files.Count > 1)
            {
                result.Success = false;
                result.Message = "一次最多上传一个文件";
                return Json(result);
            }
           
            if (size > 104857600)
            {
                result.Success = false;
                result.Message = "上传失败,文件大小超过上传限制";
                return Json(result);
            }
            var file = files[0];
            var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

            //string webRootPath = hostingEnv.WebRootPath;
            //string contentRootPath = hostingEnv.ContentRootPath;


            string filePath = hostingEnv.ContentRootPath + $@"\Upload\";

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }            

            fileName = Guid.NewGuid() + "." + fileName.Split('.')[1];           

            string fileFullName = filePath + fileName;

            using (FileStream fs = System.IO.File.Create(fileFullName))
            {
                file.CopyTo(fs);
                fs.Flush();
            }

            var picMod = new DP_Pic()
            {
                Name = fileName,
                Path = fileFullName,
                DataFlag = 1
            };

            return Json(new {
                jsonrpc = "2.0",
                id = id,
                filePath = fileFullName
            });
        }        
    }
}